<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      @submit.native.prevent
    >
      <el-form-item label="参数名称" prop="paramName">
        <el-input
          v-model="queryParams.paramName"
          placeholder="请输入参数名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <el-col :span="5" style="padding-right:0 !important">
        <left-tree ref="leftRef" @getParentId="getParentIdFunc" @cateChange="cateChange"/>
      </el-col>
      <el-col :span="19" style="padding-left:10px!important">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['base:param:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['base:param:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['base:param:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              :loading="btnLoading"
              v-hasPermi="['base:param:export']"
              >导出</el-button
            >
          </el-col>
        </el-row>

        <el-table
        :cell-style="{padding:this.tablePadding}"
          v-loading="loading"
          :data="paramList"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="参数名称" align="center" prop="paramName" />
          <el-table-column
            label="参数类型"
            align="center"
            prop="paramCategoryName"
          />
          <el-table-column
            label="数据类型"
            align="center"
            prop="dataTypeName"
          />
          <el-table-column label="计量单位" align="center" prop="unitName" />

          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['base:param:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['base:param:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改参数定义对话框 -->
        <el-dialog :close-on-click-modal="false"
          :title="title"
          :visible.sync="open"
          width="500px"
          append-to-body
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="参数分类" prop="paramCategoryId">
              <treeselect
                v-model="form.paramCategoryId"
                :options="categoryList"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择参数分类"
              />
            </el-form-item>
            <el-form-item label="参数名称" prop="paramName">
              <el-input v-model="form.paramName" placeholder="请输入参数名称" />
            </el-form-item>
            <el-form-item label="数据类型" prop="dataTypeId">
              <el-select
              style="width:100%"
                v-model="form.dataTypeId"
                placeholder="请选择数据类型"
                clearable
              >
                <el-option
                  v-for="dict in dataTypeOptions"
                  :key="dict.dataTypeId"
                  :label="dict.dataTypeName"
                  :value="dict.dataTypeId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="计量单位" prop="unitId">
              <el-select
              style="width:100%"
                v-model="form.unitId"
                placeholder="请选择计量单位"
                clearable
              >
                <el-option
                  v-for="dict in unitOption"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                  :disabled="dict.status==1"
                >
                <span style="float: left">{{ dict.dictDataAbbreviation }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictLabel}}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :loading="btnLoading" v-funThrottle="[submitForm]">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  listParam,
  getParam,
  delParam,
  addParam,
  updateParam,
  listCategory,
  getDataTypeOption,
} from "@/api/base/dataType";
import {getUnitOpiton} from "@/api/base/unit";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import LeftTree from "./components/Left.vue";
export default {
  name: "Param",
  components: { LeftTree, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      selectNames:[],
      // 参数定义表格数据
      paramList: [],
      dataTypeOptions: [], //数据类型字典
      unitOption: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paramName: null,
        paramCategoryId:null
      },
      defaultProps: {
        children: "children",
        label: "equipmentCategoryName",
      },
      categoryList: [],
      // 表单参数
      form: {},
      btnLoading:false,
      // 表单校验
      rules: {
        paramCategoryId: [
          {
            required: true,
            message: "参数定义分类不能为空",
            trigger: "blur",
          },
        ],
        dataTypeId: [
          { required: true, message: "数据类型不能为空", trigger: "blur" },
        ],
        unitId: [
          { required: true, message: "计量单位不能为空", trigger: "blur" },
        ],
        paramName: [
          { required: true, message: "参数名称不能为空", trigger: "blur" },
        ]
      },
    };
  },
  created() {
    this.getDicts("base_unit").then(response => {
      this.unitOption = response.data;
    });
    // 数据类型
    getDataTypeOption().then((response) => {
      this.dataTypeOptions = response.data;
    });
  },
  methods: {
    cateChange(){//分类有修改
      this.getCategoryList()
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.paramCategoryId,
        label: node.paramCategoryName,
        children: node.children,
      };
    },
    getCategoryList() {
      listCategory().then((response) => {
        this.categoryList = response.data;
      });
    },
    getParentIdFunc(len, id) {
      if (len > 0) {
        this.queryParams.paramCategoryId = id;
        this.getList();
      } else {
        this.loading = false;
      }
    },
    /** 查询参数定义列表 */
    getList() {
      this.loading = true;
      listParam(this.queryParams).then((response) => {
        this.paramList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paramId: null,
        paramCategoryId: null,
        dataTypeId: null,
        unitId: null,
        paramCode: null,
        paramName: null,
        sort: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.paramId);
      this.selectNames = selection.map((item) => item.paramName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.paramCategoryId=this.queryParams.paramCategoryId
      this.open = true;
      this.title = "添加参数定义";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const paramId = row.paramId || this.ids;
      getParam(paramId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改参数定义";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.btnLoading=true
          if (this.form.paramId != null) {
            updateParam(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
             this.btnLoading=false
            }).catch(()=>{
              this.btnLoading=false
            });
          } else {
            addParam(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              // this.getList();
             this.btnLoading=false
              this.$refs.leftRef.setNodeId(this.form.paramCategoryId);
            }).catch(()=>{
              this.btnLoading=false
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paramIds = row.paramId || this.ids;
      const name=row.paramName||this.selectNames
      this.$confirm(
        '是否确认删除参数名称为"' + name + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",closeOnClickModal:false,
          type: "warning",
        }
      )
        .then(function () {
          return delParam(paramIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.btnLoading=true
      this.download(
        "base/param/export",
        {
          ...this.queryParams,
        },
        `base_param.xlsx`,
        '',
        ()=>{
          this.btnLoading=false
        }
      );
    },
  },
};
</script>
